package com.ckerchina.admin.ckadmin.dao;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.ckerchina.admin.ckadmin.domain.mgr.MgrMenu;
import com.ckerchina.admin.ckadmin.domain.mgr.MgrUserAndMenu;

@Repository
public class MgrUserAndMenuDAO extends AbstractDao<MgrUserAndMenu, Long>{

	public List<MgrUserAndMenu> findAllMgrUserAndMenu() {
		return this.entityManager.createQuery("SELECT o FROM MgrUserAndMenu o ORDER BY o.sortNo ASC",
				MgrUserAndMenu.class).getResultList();
	}

	public List<MgrUserAndMenu> findUserMenuByMuserId(Long mgrUserId) {
		if (mgrUserId == null) {
			throw new IllegalArgumentException("the argument muserId is require.");
		}
		return this.entityManager
				.createQuery("SELECT o FROM MgrUserAndMenu o WHERE o.muserId = ? AND o.state = 1", MgrUserAndMenu.class)
				.setParameter(1, mgrUserId).getResultList();
	}

	public List<MgrMenu> findMgrMenuByMuserId(Long mgrUserId) {
		if (mgrUserId == null) {
			throw new IllegalArgumentException("the argument muserId is require.");
		}
		return this.entityManager
				.createQuery(
						"SELECT t FROM MgrUserAndMenu o,MgrMenu t WHERE o.menuId = t.id AND o.muserId = ? AND o.state = 1 ORDER BY t.sortNo ASC",
						MgrMenu.class).setParameter(1, mgrUserId).getResultList();
	}

	public List<MgrUserAndMenu> findAllByMuserId(Long mgrUserId) {
		if (mgrUserId == null) {
			throw new IllegalArgumentException("the argument muserId is require.");
		}
		return this.entityManager
				.createQuery("SELECT o FROM MgrUserAndMenu o WHERE o.muserId = ?", MgrUserAndMenu.class)
				.setParameter(1, mgrUserId).getResultList();
	}

	public List<MgrUserAndMenu> findAllByMenuId(Long mgrMenuId) {
		if (mgrMenuId == null) {
			throw new IllegalArgumentException("the argument muserId is require.");
		}
		return this.entityManager
				.createQuery("SELECT o FROM MgrUserAndMenu o WHERE o.menuId = ?", MgrUserAndMenu.class)
				.setParameter(1, mgrMenuId).getResultList();
	}

	public MgrUserAndMenu findByMuserIdAndMenuId(Long mgrUserId, Long mgrMenuId) {
		if (mgrUserId == null || mgrMenuId == null) {
			return null;
		}
		List<MgrUserAndMenu> list = this.entityManager
				.createQuery("SELECT o FROM MgrUserAndMenu o WHERE o.muserId = ? AND o.menuId =?", MgrUserAndMenu.class)
				.setParameter(1, mgrUserId).setParameter(2, mgrMenuId).getResultList();
		return list.size() > 0 ? list.get(0) : null;
	}
}
